package com.mvc.web.order.controller;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mvc.web.common.base.BaseController;
import com.mvc.web.common.statics.Route;
import com.mvc.web.common.statics.Static;
import com.mvc.web.common.utils.AnnotationDealUtil;
import com.mvc.web.common.utils.OSSManageUtil;
import com.mvc.web.common.utils.PinyinUtils;
import com.mvc.web.common.utils.ToolsUtils;
import com.mvc.web.order.controller.validate.FileVoValidator;
import com.mvc.web.order.service.OrderService;
import com.mvc.web.order.vo.FileVo;
import com.mvc.web.order.vo.GpsVo;
import com.mvc.web.order.vo.MaterialVo;
import com.mvc.web.order.vo.OrderForm;
import com.mvc.web.order.vo.OrderVo;
import com.mvc.web.order.vo.ResultVo;

/** 
 * @ClassName: OrderController 
 * @Description: 订单相关接口控制器
 * @author: 白海安(baiha@jizhicar.com) 2017年8月28日 下午4:23:05
 * @version V1.0
 */
@Controller
public class OrderController extends BaseController{
	
	@Autowired
	private OrderService orderService;
	@Autowired
	private FileVoValidator fileVoValidator;// 参数校验器
	
	/** 
	 * @Description: 获取订单列表 
	 * @author 白海安(baiha@jizhicar.com) 2017年8月28日 下午4:23:33
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_LIST,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String list(OrderForm vo,Integer currentPage,HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			if (currentPage == null) {
				currentPage = 1;
			}
			int limit =10;
			vo.setLimit(limit);
			vo.setStart((currentPage - 1) * 10);
			vo.setUid(getIdFormCookie(request, "HYBBU"));
			List<OrderVo> list = orderService.getList(vo);
			long count = orderService.getCount(vo);
			long totalPages = count % limit == 0 ? count / limit : count
					/ limit + 1;
			res.put("errorCode", 0);
	    	res.put("errorMsg", "success");
	    	res.put("requestId", requestId);
	    	ResultVo result = new ResultVo();
	    	result.setCurrentPage(currentPage);
	    	result.setTotalPages(totalPages);
	    	result.setData(list);
	    	res.put("data", JSON.toJSON(result));
			return res.toString();
		} catch (Exception e) {
			return Error("order list error: ", e);
		}
	}
	/** 
	 * @Description: 订单创建 
	 * @author 白海安(baiha@jizhicar.com) 2017年8月31日 下午5:58:04
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_CREATE,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String create(OrderVo vo,HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			Map<String,  Object> result = AnnotationDealUtil.validate(vo);
			if (result.get("result").equals(false)) {
				res.put("errorCode", 1002);
				res.put("errorMsg", result.get("message"));
				res.put("requestId", requestId);
				return res.toString();
			}
			//校验当前车主是否有未完成的货运单，如果有不能提交新的货运单
			int count = orderService.getCountForValidate(vo.getCarOwnerPhone());
			if(count>0){
				res.put("errorCode", 1003);
				res.put("errorMsg", "该车主尚有未送达的货运单，不能添加新的货运单");
				res.put("requestId", requestId);
				return res.toString();
			}
			int uid = getIdFormCookie(request, "HYBBU");
			vo.setCreateId(uid);
			vo.setModifyId(uid);
			vo.setCtime(System.currentTimeMillis()/1000);
			vo.setMtime(System.currentTimeMillis()/1000);
			vo.setInitial(PinyinUtils.getStartPinYin(vo.getCarOwnerName()));
			vo.setOrderNo(new SimpleDateFormat("yyyyMMdd").format(new Date())+ToolsUtils.letter2Num(UUID.randomUUID().toString().replace("-", "")));
			int orderId = orderService.create(vo);
			vo.setOrderId(orderId);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			logger.info("requestId:"+requestId+"order create: "+JSON.toJSONString(vo));
			vo=new OrderVo();
			vo.setOrderId(orderId);
			res.put("data", JSON.toJSON(vo));
			return res.toString();
		} catch (Exception e) {
			return Error("order create error: ", e);
		}
	}
	/** 
	 * @Description: 订单提交 
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 上午11:03:29
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_COMMIT,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String commit(@RequestParam(required=true)Integer orderId,HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			int uid = getIdFormCookie(request, "HYBBU");
			orderService.commit(orderId,uid);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			logger.info("order commit: "+"requestId:"+requestId+" orderId:"+orderId+" uid:"+uid);
			return res.toString();
		} catch (Exception e) {
			return Error("order commit error: ", e);
		}
	}
	/** 
	 * @Description: 查询详情信息 
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 下午2:47:44
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_DETAIL,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String getDetail(@RequestParam(required=true)Integer orderId){
		JSONObject res = new JSONObject();
		try {
			OrderVo vo = orderService.getDetail(orderId);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			res.put("data", JSON.toJSON(vo));
			return res.toString();
		} catch (Exception e) {
			return Error("order create error: ", e);
		}
	}
	/** 
	 * @Description: 修改 
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 下午2:15:54
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_UPDATE,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String update(@RequestParam(required=true)Integer orderId, OrderVo vo,HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			Map<String,  Object> result = AnnotationDealUtil.validate(vo);
			if (result.get("result").equals(false)) {
				res.put("errorCode", 1002);
				res.put("errorMsg", result.get("message"));
				res.put("requestId", requestId);
				return res.toString();
			}
			//校验当前车主是否有未完成的货运单，如果有不能提交新的货运单
			int count = orderService.getCountForValidate(vo.getCarOwnerPhone());
			if(count>0){
				res.put("errorCode", 1003);
				res.put("errorMsg", "该车主尚有未送达的货运单，不能添加新的货运单");
				res.put("requestId", requestId);
				return res.toString();
			}
			int uid = getIdFormCookie(request, "HYBBU");
			vo.setModifyId(uid);
			vo.setMtime(System.currentTimeMillis()/1000);
			vo.setInitial(PinyinUtils.getStartPinYin(vo.getCarOwnerName()));
			orderService.update(vo);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			logger.info("requestId:"+requestId+"order update: "+JSON.toJSONString(vo));
			return res.toString();
		} catch (Exception e) {
			return Error("order create error: ", e);
		}
	}
	/** 
	 * @Description: 上传照片 
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 上午11:30:56
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_UPLOAD,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam(required=true)Integer orderId,
						 @RequestParam(required=true)MultipartFile file,
						 FileVo vo,
						 BindingResult validateResult, 
						 HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			if (file == null || file.isEmpty()) {
				res.put("errorCode", 1002);
				res.put("errorMsg", "图片数据为空");
				res.put("requestId", requestId);
				return res.toString();
			}
			// 验证参数
			fileVoValidator.validate(vo, validateResult);
			if (validateResult.hasErrors()) {
				res.put("errorCode", 1002);
				res.put("errorMsg", validateResult.getAllErrors().get(0).getDefaultMessage());
				res.put("requestId", requestId);
				return res.toString();
			}
			long size = file.getSize();
			String file_id = OSSManageUtil.getKey(file.getOriginalFilename());
			if (ToolsUtils.isEmpty(file_id)) {
				res.put("errorCode", 1003);
				res.put("errorMsg", "图片格式错误");
				res.put("requestId", requestId);
				return res.toString();
			}
			// 上传到阿里云
			OSSManageUtil.uploadFile(file.getInputStream(), file_id);
			// 删除之前的图片集
			if (ToolsUtils.isNotEmpty(vo.getFileId())) {
				orderService.deleteFile(vo.getFileId());
			}
			String file_name = URLDecoder.decode(vo.getFileName(), "utf-8");
			// 赋值
			vo.setFileName(file_name);
			vo.setFileId(file_id);
			vo.setFileSize(size);
			vo.setCtime(System.currentTimeMillis() / 1000);
			vo.setMtime(System.currentTimeMillis() / 1000);
			orderService.uploadFile(vo);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			int uid = getIdFormCookie(request, "HYBBU");
			logger.info("requestId:"+requestId+" uid:"+uid +" order upload: "+JSON.toJSONString(vo));
			vo=new FileVo();
			vo.setFileId(file_id);
			res.put("data", JSON.toJSON(vo));
			return res.toString();
		} catch (Exception e) {
			return Error("order upload error: ", e);
		}
	}
	/** 
	 * @Description: 批量删除照片 
	 * @author 白海安(baiha@jizhicar.com) 2017年9月6日 上午10:24:27
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_UPLOAD_DEL,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String deleteFile(@RequestParam(required=true)String fileIds,HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			if(ToolsUtils.isNotEmpty(fileIds)){
				orderService.deleteFile(fileIds);
			}
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			int uid = getIdFormCookie(request, "HYBBU");
			logger.info("requestId:"+requestId+" uid:"+uid +" order delete file: "+fileIds);
			return res.toString();
		} catch (Exception e) {
			return Error("order deleteFile error: ", e);
		}
	}
	/** 
	 * @Description: 获取图片集合 
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 下午3:16:33
	 * @version V1.0
	 */
	@RequestMapping(value = Route.ORDER_FILE, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String listfile(@RequestParam(required = true) Integer orderId) {
		JSONObject res = new JSONObject();
		try {
			List<FileVo> list_= new ArrayList<FileVo>();
			int status = orderService.getStatusById(orderId);
			if(status==-1){
				res.put("errorCode", 0);
				res.put("errorMsg", "success");
				res.put("requestId", requestId);
				res.put("data", new ArrayList<>());
			}else if(status<3){
				//出货凭证
				FileVo file = new FileVo();
				List<FileVo> list = orderService.getFileList(orderId,1);
				List<MaterialVo> material_list = Static.Material_1;
				file.setData(list);
				file.setMaterialList(material_list);
				file.setMaterialType(1);
				list_.add(file);
			}else{
				//出货凭证、送达凭证
				FileVo file = new FileVo();
				List<FileVo> list = orderService.getFileList(orderId,1);
				List<MaterialVo> material_list = Static.Material_1;
				file.setData(list);
				file.setMaterialList(material_list);
				file.setMaterialType(1);
				list_.add(file);
				FileVo file4 = new FileVo();
				List<FileVo> list_4 = this.orderService.getFileList(orderId,2);
				List<MaterialVo>  material_list4 = Static.Material_2;
				file4.setData(list_4);
				file4.setMaterialList(material_list4);
				file4.setMaterialType(4);
				list_.add(file4);
			}
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			res.put("data", list_);
			return res.toString();
		} catch (Exception e) {
			return Error("order listfile error: ", e);
		}

	}
	/** 
	 * @Description: 确认送达 
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 下午3:55:14
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_DELIVERY,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String delivery(@RequestParam(required=true)Integer orderId,HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			int uid = getIdFormCookie(request, "HYBBU");
			orderService.delivery(orderId,uid);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			logger.info("order delivery: "+"requestId:"+requestId+" orderId:"+orderId+" uid:"+uid);
			return res.toString();
		} catch (Exception e) {
			return Error("order delivery error: ", e);
		}
	}
	/** 
	 * @Description: 存储定位信息
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 下午3:55:14
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_GPS,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String gps(@RequestParam(required=true)String longitude,
					  @RequestParam(required=true)String latitude,
					  @RequestParam(required=true)String address,
					  HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			int uid = getIdFormCookie(request, "HYBBU");
			orderService.gps(longitude,latitude,uid,address);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			logger.info("order gps: "+"requestId:"+requestId+" longitude:"+longitude+" latitude:"+latitude+" uid:"+uid);
			return res.toString();
		} catch (Exception e) {
			return Error("order gps error: ", e);
		}
	}
	/** 
	 * @Description: 获取定位信息
	 * @author 白海安(baiha@jizhicar.com) 2017年9月4日 下午3:55:14
	 * @version V1.0
	 */
	@RequestMapping(value=Route.ORDER_LIST_GPS,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String listgps(@RequestParam(required=true)Integer orderId,HttpServletRequest request){
		JSONObject res = new JSONObject();
		try {
			List<GpsVo> list = orderService.getGps(orderId);
			res.put("errorCode", 0);
			res.put("errorMsg", "success");
			res.put("requestId", requestId);
			res.put("data", list);
			return res.toString();
		} catch (Exception e) {
			return Error("order listgps error: ", e);
		}
	}
}
